<?php
/**
 * @file
 * All front end related stuff
 */

/**
 * Implementation of hook_view().
 */
function race_view($node, $teaser = FALSE, $page = FALSE) {
  drupal_add_css(drupal_get_path('module', 'race') .'/race.css', 'module', 'all', FALSE);
  global $user;
  if ($node->state == Constants::$STATE_SIGNUP) {
    race_view_signup($node);
  }
  else if ($node->state == Constants::$STATE_ASSIGNMENT) {
    race_view_assigned($node);
  } else {
    var_dump($node);
    throw new Exception("Unknown state type in node.");
  }
  return $node;
}

/**
 * Displays the form for the normal user.
 */
function race_view_signup($node) {
    global $user;
    $node = node_prepare($node, $teaser);
    $signups = _get_signups($node);
    $config = _get_config($node);
    
    if (user_access('admin')) {
	    $node->content['admin'] = array(
	      '#value' => "<a href='".base_path()."race/".$node->nid."/admin'>ADMIN</a>",
	      '#weight' => -1
	    );
    }
    
    // body
    $node->content['body'] = array(
      '#value' => $node->body,
      '#weight' => 0
    );
    
    // signup form / status
    if (!user_access('sign up')) {
      $signupValue = t("You can not sign up unless you're logged in.")." ";
      $signupValue .= "<a href='".base_path()."user/login'>".t('login')."</a> / <a href='".base_path()."user/register'>".t('register')."</a>";
    }
    else if (_is_user_signed_up($signups, $user->name)) {
      $signupValue = t("You're signed up.")." ";
      $signupValue .= "<a href='". base_path() ."race/signoff/". $node->nid ."'>".t("sign off")."</a>";
    }
    else if (user_access("sign up")) {
      $signupValue = t("You're not signed up.")." ";
      $signupValue .= drupal_get_form('race_sign_on', $node->nid);
    }
    $node->content['signup'] = array(
      '#value' => $signupValue,
      '#weight' => 1
    );
    
    // signup list
    $listTitle = t("Sign up list").":<br />";
    $node->content['list'] = array(
      '#value' => $listTitle._xsl_signuplist_user($signups),
      '#weight' => 2
    );
    
    $node->content['list_space'] = array(
      '#value' => "<br /><br />",
      '#weight' => 2
    );
}

function race_view_assigned($node) {
  global $user;
  $node = node_prepare($node, $teaser);
  $assignments = _get_assignments($node);
  $config = _get_config($node);
  $signups = _get_signups($node);
  
    if (user_access('admin')) {
	    $node->content['admin'] = array(
	      '#value' => "<a href='".base_path()."race/".$node->nid."/admin'>ADMIN</a>",
	      '#weight' => -1
	    );
    }
    
    $node->content['body'] = array(
      '#value' => $node->body,
      '#weight' => 0
    );
  
  $node->content['assignmentlist'] = array(
    '#value' => _assignmentlist_user($assignments, $config, $signups, $node->nid),
    '#weight' => 0
  );
  
  $node->content['key'] = array(
    '#value' => _get_key_stati(),
    '#weight' => 1
  );
  
  $node->content['clubs'] = array(
    '#value' => _get_key_clubs($config),
    '#weight' => 2
  );
}

/**
 * sign on form
 */
function race_sign_on($form_state, $nid) {
  $node = node_load($nid);
  $config = _get_config($node);
  
  $form['signup'] = array(
    '#title'=> t("sign up"),
    '#type'=>'fieldset',
    '#collapsible'=> FALSE,
    '#collapsed' => FALSE,
  );
  
  $form['signup'] ['nid'] = array(
    '#type' => 'hidden',
    '#value' => $nid,
  );
  
  foreach ($config->form->option as $formElement) {
    $a = $formElement->attributes();
    if ($a['type'] == "textarea") {
      $id = (String) $a['id'];
      $form['signup'][$id] = array(
        '#type' => 'textarea',
        '#rows' => $a['rows'],
        '#maxlength' => $a['maxlength'],
        '#description' => $a['description'],
        '#title' => $a['title'],
      );
    }
    if ($a['type'] == "checkbox") {
      $id = (String) $a['id'];
      $form['signup'][$id] = array(
        '#type' => 'checkbox',
        '#default_value' => 0,
        '#title' => $a['title'],
        '#description' => $a['description'],
      );
    }
    if ($a['type'] == "boatselect") {
      $form['signup']["boatselect"] = array(
        '#type' => 'select',
        '#title' => $a['title'],
        '#description' => $a['description'],
    	'#options' => _get_boats_options($config),
      );    
    }
    if ($a['type'] == "experience") {
      $form['signup']["experience"] = array(
        '#type' => 'radios',
        '#title' => $a['title'],
        '#description' => $a['description'],
    	'#options' => _get_experience_options($formElement),
      );    
    }
  }

  $form['signup'] ['submit'] = array(
    '#type' => 'submit',
    '#value' => t("sign up")
  );
  
  return $form;
}

function _get_boats_options($config) {
  $out[0] = t("---");
  foreach (_get_boats($config) as $key => $result) {
    $id = (string) $result['id'];
    $out[$id] = (string) $result['name'];
  }
  return $out;
}

function _get_experience_options(SimpleXMLElement $experience) {
  $out = array();
  foreach ($experience->choice as $choice) {
    $out[] = (String) $choice;
  }
  return $out;
}



function race_sign_on_validate($form, &$form_state)
{ 
}

/** 
  * callback from form to sign on
  */
function race_sign_on_submit($form, &$form_state)
{ 
  $nid = $form_state["values"]["nid"];
  _sign_on($nid, $form_state["values"]);
  drupal_set_message(t('Your form has been submitted'));
  $form_state['redirect'] = 'node';
}

function _xsl_signuplist_user($signups) { 
  $file = drupal_get_path('module', "race").DIRECTORY_SEPARATOR."xsl".DIRECTORY_SEPARATOR."signup_list.xml";
  $xsl = new DOMDocument();
  $xsl->load($file);
  return _xsl($signups->asXML(), $xsl);
}

function _assignmentlist_user(SimpleXMLElement $assignments, SimpleXMLElement $config, SimpleXMLElement $signups, $nid) { 
  global $user;
  $html = "";
  foreach (_get_boats($config) as $boatConfig) {
    $club = $boatConfig['club'];
    $html .= "<div class='boat $club'>";
    $html .= "<div class='boatname'>".$boatConfig['name']."</div>";
    $assignees = _get_boat_assignments_by_id($assignments, $boatConfig['id']);
    for ($i=0; $i<(int)$boatConfig['places']; $i++) {
      if (sizeof($assignees) > $i) {
        $userName = $assignees->signup[$i]["user"];
        $html .= "<div class='place belegt'>";
        $html .= $userName." ";
        $html .= _get_experience($signups, $userName);
        if (user_access('admin') || $user->name == $userName) {
          $html .= _get_link_signoff_from_boat($nid, $boatConfig['id'])." ";
        }
        $html .= "</div>";
      } else {
        $html .= "<div class='place frei'>";
        if (user_access('sign up')) {
          $html .= _get_link_signup_for_boat($nid, $boatConfig['id']);
        } else {
          $html .= "&nbsp;";
        }
        $html .= "</div>";
      }
    }
    $html .= "</div>";
  }
  return $html;
}

function _xsl($xmlString, DOMDocument $xsl) {
  $xml = new DOMDocument();
  $xml->loadXML($xmlString);
  
  $processor = new XSLTProcessor();
  $processor->importStyleSheet($xsl);
    
  return $processor->transformToXML($xml);
}

function _get_key_stati() {
  return "<table class='key'>
		<tbody><tr><th>Stati</th><th> </th></tr>
		<tr><td class='belegt'> </td><td>belegt</td></tr>
		<tr><td class='frei'> </td><td>frei</td></tr>
		</tbody></table>";
}

function _get_key_clubs(SimpleXMLElement $config) {
  $html = "<table class='key'><tr><th>Clubs</th><th></th></tr>";
  $clubs = _get_clubs($config);
  foreach ($clubs as $club) {
    $html .= "<tr><td class='$club'></td><td>$club</td></tr>";
  }
  $html .= "</table>";
  return $html;	
}

function _get_link_signup_for_boat($nid, $boatId) {
  return "<a href='".base_path()."race/signup_boat/".$nid."/".$boatId."'>".t("sign up")."</a>";
}

function _get_link_signoff_from_boat($nid, $boatId) {
  return "<a href='".base_path()."race/signoff_boat/".$nid."/".$boatId."'>".t("sign off")."</a>";
}